<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="GrantonZhuang's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="动态代理是什么
PS：对于动态代理了解的同志可以跳过这一个 part

大家都知道，retrofit 内部应用了动态代理技术，那么动态代理又是什么？以下来自 Oracle 的官方文档 以及我自己的渣翻译">
<meta property="og:type" content="article">
<meta property="og:title" content="动态代理与Retrofit">
<meta property="og:url" content="https://grantonzhuang.github.io/2016/04/19/动态代理与Retrofit/index.html">
<meta property="og:site_name" content="GrantonZhuang's Blog">
<meta property="og:description" content="动态代理是什么
PS：对于动态代理了解的同志可以跳过这一个 part

大家都知道，retrofit 内部应用了动态代理技术，那么动态代理又是什么？以下来自 Oracle 的官方文档 以及我自己的渣翻译">
<meta property="og:image" content="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解1-定义一个接口.png">
<meta property="og:image" content="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解2-实现接口-InvocationHandler.png">
<meta property="og:image" content="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解-3-Proxy.newProxyInstance-创建代理类.png">
<meta property="og:image" content="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解4-代理类的接口方法的具体调用过程.png">
<meta property="og:updated_time" content="2016-07-29T14:58:06.908Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="动态代理与Retrofit">
<meta name="twitter:description" content="动态代理是什么
PS：对于动态代理了解的同志可以跳过这一个 part

大家都知道，retrofit 内部应用了动态代理技术，那么动态代理又是什么？以下来自 Oracle 的官方文档 以及我自己的渣翻译">
<meta name="twitter:image" content="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解1-定义一个接口.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://grantonzhuang.github.io/2016/04/19/动态代理与Retrofit/"/>

  <title> 动态代理与Retrofit | GrantonZhuang's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">GrantonZhuang's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                动态代理与Retrofit
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-04-19T23:00:06+08:00" content="2016-04-19">
              2016-04-19
            </time>
          </span>

          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="动态代理是什么"><a href="#动态代理是什么" class="headerlink" title="动态代理是什么"></a>动态代理是什么</h2><blockquote>
<p>PS：对于动态代理了解的同志可以跳过这一个 part</p>
</blockquote>
<p>大家都知道，retrofit 内部应用了动态代理技术，那么动态代理又是什么？以下来自 <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html" target="_blank" rel="external">Oracle 的官方文档</a> 以及我自己的渣翻译</p>
<a id="more"></a>
<blockquote>
<p>A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.</p>
<p>在运行时， <code>动态代理类</code> 实现了一个或者一组接口，目的是，其中任何一个接口的实例的方法调用将会被指派到统一的另一个接口的方法中。（译注：这里的另一个接口方法指的是 <code>InvocationHandler</code> 的  <code>invoke()</code> 方法）</p>
<p>Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools.</p>
<p>因此，一个动态代理类可以被用于以下场景：为一个或者一组接口创建一个类型安全的代理对象，而不需要预先生成代理类（比如通过编译时工具）。</p>
<p>Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance’s invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.</p>
<p>使用动态代理类的实例进行的方法调用，会被指派到这个实例的 <code>InvocationHandler</code> ，通过一个  <code>java.lang.reflect.Method</code> 的对象指明这个方法和其参数列表（译注：这也就是常见的反射啦）。</p>
</blockquote>
<p>翻译得不咋地，各位兄台还是看原文把，或者来张图：</p>
<p>首先我们需要定义一个接口：</p>
<p><img src="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解1-定义一个接口.png" alt="定义一个接口"></p>
<p>第二步是实现接口 <code>InvocationHandler</code> ，这个实现类决定了第一步提到的接口的方法在调用的时候的做法。</p>
<p><img src="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解2-实现接口-InvocationHandler.png" alt="实现接口 InvocationHandler"></p>
<p>第三步是创建出代理类，使用 <code>Proxy.newProxyInstance(ClassLoader, interfaces[], InvocationHandlerImpl)</code> 方法创建一个代理类，这个类在创建过程中会实现传入的所有接口，并且会向生成的代理类注入传入的 <code>InvocationHandlerImpl</code> 。</p>
<p><img src="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解-3-Proxy.newProxyInstance-创建代理类.png" alt="Proxy.newProxyInstance 创建代理类"></p>
<p>最后看代理类的接口方法的具体调用过程</p>
<p><img src="http://blog.qiji.tech/wp-content/uploads/2016/04/动态代理图解4-代理类的接口方法的具体调用过程.png" alt="代理类的接口方法的具体调用过程"></p>
<p>具体的过程在图中已经有所描述，传参数啥的仔细看文档即可，</p>
<p><strong>比较重点的就是 <code>InvocationHandler</code> 中覆写的 <code>invoke()</code> 方法，在进行原本的方法调用之前或者之后，可以做点事情。</strong></p>
<p>比如权限验证。假设存在 <code>RoleOne</code> 和 <code>RoleTwo</code> 两种角色，</p>
<p>那么 <code>RoleOneTaskRunner</code> ， <code>RoleTwoTaskRunner</code> 的权限验证是全局的（也就是统一的），在  <code>invoke()</code> 方法中动手脚，可以避免在两个 <code>TaskRunner</code> 的实现类里写重复的代码，同时起到的作用为，将 <code>权限验证机制</code> 和 <code>具体业务逻辑</code> 分开，这也是面向切面编程实现的常用手段。</p>
<h2 id="Retrofit-对动态代理的应用"><a href="#Retrofit-对动态代理的应用" class="headerlink" title="Retrofit 对动态代理的应用"></a>Retrofit 对动态代理的应用</h2><h3 id="Retrofit-java-部分"><a href="#Retrofit-java-部分" class="headerlink" title="Retrofit.java 部分"></a><code>Retrofit.java</code> 部分</h3><p>Retrofit 的用法相信大家也很熟悉，全局初始化 <code>Retrofit</code> 实例以后，大体上分为三步:</p>
<ul>
<li>将后台 API 服务声明为接口，将后台 API 接口调用声明为接口方法</li>
<li>使用 <code>create()</code> 方法创建接口的实现类</li>
<li>使用实现类调用对应的方法实现网络访问</li>
</ul>
<p>实际上，这个过程就和动态代理的过程一毛一样有木有:</p>
<ul>
<li>将后台 API 服务声明为接口，将后台 API 接口调用声明为接口方法</li>
<li>使用 <code>create()</code> 方法创建接口的实现类（其实就是代理类）</li>
<li>使用实现类调用对应的方法实现网络访问（这里肯定是调用到了 <code>InvocationHandler</code> 的 <code>invoke()</code> 方法）</li>
</ul>
<p>所以，赶紧跳进源码，查看 <code>create()</code> 方法都做了些啥，了解一下 Retrofit 是如何运用动态代理吧。</p>
<p>源码部分， <code>Retrofit.java$create()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">create</span><span class="params">(<span class="keyword">final</span> Class&lt;T&gt; service)</span> </span>&#123;</div><div class="line">	<span class="comment">// 检查传入的 service 是不是一个接口</span></div><div class="line">    Utils.validateServiceInterface(service);</div><div class="line">    <span class="keyword">if</span> (validateEagerly) &#123;</div><div class="line">      eagerlyValidateMethods(service);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> (T) Proxy.newProxyInstance(service.getClassLoader(), <span class="keyword">new</span> Class&lt;?&gt;[] &#123; service &#125;,<span class="keyword">new</span> InvocationHandler() &#123;</div><div class="line">    	<span class="keyword">private</span> <span class="keyword">final</span> Platform platform = Platform.get();</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object... args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</div><div class="line">            <span class="comment">// If the method is a method from Object then defer to normal invocation.</span></div><div class="line">            <span class="keyword">if</span> (method.getDeclaringClass() == Object.class) &#123;</div><div class="line">                <span class="keyword">return</span> method.invoke(<span class="keyword">this</span>, args);</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">if</span> (platform.isDefaultMethod(method)) &#123;</div><div class="line">                <span class="keyword">return</span> platform.invokeDefaultMethod(method, service, proxy, args);</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">return</span> loadMethodHandler(method).invoke(args);</div><div class="line">        &#125;</div><div class="line">    &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>分析一下这个方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Utils.validateServiceInterface(service);</div></pre></td></tr></table></figure>
<p>其实就是检查一下传入的 service 对象是不是一个接口，如果不是接口则抛出异常。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (validateEagerly) &#123;</div><div class="line">	eagerlyValidateMethods(service);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果 <code>ruguovalidateEagerly</code> 为 true ，则验证接口里的每一个方法，来看 <code>eagerlyValidateMethods()</code> 方法的定义：</p>
<p><code>Retrofit.java$eagerlyValidateMethods()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">eagerlyValidateMethods</span><span class="params">(Class&lt;?&gt; service)</span> </span>&#123;</div><div class="line">	Platform platform = Platform.get();</div><div class="line">    <span class="keyword">for</span> (Method method : service.getDeclaredMethods()) &#123;</div><div class="line">    	<span class="keyword">if</span> (!platform.isDefaultMethod(method)) &#123;</div><div class="line">        	loadMethodHandler(method);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>首先获取到平台，是<strong>接口内部可实现方法</strong>的 Java8 还是 Android。</p>
<p>换言之，目前的 Android 平台下的话， <code>!platform.isDefaultMethod(method)</code> 会一直返回 true，也就是会为每一个接口方法加载一个 <code>MethodHandler</code>。</p>
<p>而加载 <code>MethodHandler</code> 则采用了缓存机制。</p>
<p><code>Retrofit.java$loadMethodHandler()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">MethodHandler&lt;?&gt; loadMethodHandler(Method method) &#123;</div><div class="line">	MethodHandler&lt;?&gt; handler;</div><div class="line">    <span class="keyword">synchronized</span> (methodHandlerCache) &#123;</div><div class="line">    	handler = methodHandlerCache.get(method);</div><div class="line">        <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</div><div class="line">        	handler = MethodHandler.create(<span class="keyword">this</span>, method);</div><div class="line">        	methodHandlerCache.put(method, handler);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> handler;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这个 <code>MethodHandler</code> 也很关键，稍后再说，先回到我们的 <code>create()</code> 方法，这个方法最后返回了一个代理类。我们来看关键的 <code>invoke()</code> 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (method.getDeclaringClass() == Object.class) &#123;</div><div class="line">	<span class="keyword">return</span> method.invoke(<span class="keyword">this</span>, args);</div><div class="line">&#125;</div><div class="line"><span class="keyword">if</span> (platform.isDefaultMethod(method)) &#123;</div><div class="line">	<span class="keyword">return</span> platform.invokeDefaultMethod(method, service, proxy, args);</div><div class="line">&#125;</div><div class="line"><span class="keyword">return</span> loadMethodHandler(method).invoke(args);</div></pre></td></tr></table></figure>
<ul>
<li>如果方法调用来自于 <code>Object</code> ，比如 <code>hashCode()</code> , <code>equals()</code> 等，正常调用</li>
<li>如果方法调用是调用接口的内部已经实现的方法，正常调用</li>
<li>除去以上两种情况，这里与上面提到的直接使用反射机制的 <code>method.invoke()</code> 不同，这里将 <code>method</code> 对象封装到了 <code>MethodHandler</code> 中，然后调用了 <code>MethodHandler.invoke(args)</code> 这个方法。</li>
</ul>
<h3 id="MethodHandler-java-部分"><a href="#MethodHandler-java-部分" class="headerlink" title="MethodHandler.java 部分"></a><code>MethodHandler.java</code> 部分</h3><p>所以，我们需要查看 <code>MethodHandler.invoke(args)</code> 都做了啥，在此之前，先看看 <code>MethodHandler</code> 是如何创建的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">static</span> MethodHandler&lt;?&gt; create(Retrofit retrofit, Method method) &#123;</div><div class="line">    CallAdapter&lt;Object&gt; callAdapter = (CallAdapter&lt;Object&gt;) createCallAdapter(method, retrofit);</div><div class="line">    Type responseType = callAdapter.responseType();</div><div class="line">    Converter&lt;ResponseBody, Object&gt; responseConverter =</div><div class="line">    			(Converter&lt;ResponseBody, Object&gt;) createResponseConverter(method, retrofit, responseType);</div><div class="line">    RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit);</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MethodHandler&lt;&gt;(retrofit, requestFactory, callAdapter, responseConverter);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里有初始化 <code>CallAdapter</code> , <code>Converter</code> 等，但不是目前的重点，重点是这一行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit);</div></pre></td></tr></table></figure>
<p>查看这个 <code>RequestFactoryParser.parse()</code> 方法的定义</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">static</span> RequestFactory <span class="title">parse</span><span class="params">(Method method, Type responseType, Retrofit retrofit)</span> </span>&#123;</div><div class="line">    RequestFactoryParser parser = <span class="keyword">new</span> RequestFactoryParser(method);</div><div class="line">    parser.parseMethodAnnotations(responseType);</div><div class="line">    parser.parseParameters(retrofit);</div><div class="line">    <span class="keyword">return</span> parser.toRequestFactory(retrofit.baseUrl());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里将 <code>method</code> 对象包含的信息（绝大多数信息是注解上的，如 <code>@GET(&#39;url&#39;)</code> ， <code>@Path(“id”) String id</code>）这些注解信息全部解析出来，赋值给了 <code>RequestFactory</code> 对象。</p>
<p>最后再看 <code>MethodHandler.invoke()</code> 方法，这里会把<strong>请求的所有信息</strong>都交给 <code>callAdapter</code> 处理，最后返回一个 <code>Call</code> 对象，这个 <code>Call</code> 对象我理解为<strong>后台 API 调用</strong>这个动作，不知道是否有误，如果有误请指出。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function">Object <span class="title">invoke</span><span class="params">(Object... args)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> callAdapter.adapt(<span class="keyword">new</span> OkHttpCall&lt;&gt;(retrofit, requestFactory, responseConverter, args));</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="一个栗子"><a href="#一个栗子" class="headerlink" title="一个栗子"></a>一个栗子</h3><p>借用 <a href="http://square.github.io/retrofit/" target="_blank" rel="external">官方文档</a> 的一个栗子:</p>
<p>定义接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">GitHubService</span> </span>&#123;</div><div class="line">	<span class="meta">@GET</span>(<span class="string">"users/&#123;user&#125;/repos"</span>)</div><div class="line">    Call&lt;List&lt;Repo&gt;&gt; listRepos(<span class="meta">@Path</span>(<span class="string">"user"</span>) String user);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>创建代理类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">    .baseUrl(<span class="string">"https://api.github.com/"</span>)</div><div class="line">    .build();</div><div class="line"></div><div class="line">GitHubService service = retrofit.create(GitHubService.class);</div></pre></td></tr></table></figure>
<p>所以我们可以将这里的 <code>service</code> 对象理解为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Proxy.newProxyInstance(classLoader, <span class="keyword">new</span> Class&lt;?&gt;[] &#123;GitHubService.class&#125;, <span class="keyword">new</span> InvocationHandler()&#123;...&#125;)</div></pre></td></tr></table></figure>
<p>的返回值。</p>
<p>调用代理类的接口方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Call&lt;List&lt;Repo&gt;&gt; repos = service.listRepos(<span class="string">"octocat"</span>);</div></pre></td></tr></table></figure>
<p>这里的 <code>repos</code> 对象可以理解为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">Retrofit.loadMethodHandler(methodListRepos).invoke(<span class="keyword">new</span> Object[]&#123;<span class="string">"octocat"</span>&#125;);</div></pre></td></tr></table></figure>
<p>的返回值。</p>
<p>至于 <code>repos</code> 后续的处理，涉及太遥远，有心无力啊…因此不在本文讨论的范围内。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/01/22/Hello-Android-DataBinding/" rel="next" title="Android DataBinding 笔记">
                <i class="fa fa-chevron-left"></i> Android DataBinding 笔记
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/04/24/BlurImageView的基本使用和源码解析/" rel="prev" title="BlurImageView的基本使用和源码解析">
                BlurImageView的基本使用和源码解析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww1.sinaimg.cn/mw690/6e8939a6gw1f3g1u1mc6lj20hs0hsmxf.jpg"
               alt="Granton Zhuang" />
          <p class="site-author-name" itemprop="name">Granton Zhuang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives/index.html">
              <span class="site-state-item-count">26</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#动态代理是什么"><span class="nav-number">1.</span> <span class="nav-text">动态代理是什么</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Retrofit-对动态代理的应用"><span class="nav-number">2.</span> <span class="nav-text">Retrofit 对动态代理的应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Retrofit-java-部分"><span class="nav-number">2.1.</span> <span class="nav-text">Retrofit.java 部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MethodHandler-java-部分"><span class="nav-number">2.2.</span> <span class="nav-text">MethodHandler.java 部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一个栗子"><span class="nav-number">2.3.</span> <span class="nav-text">一个栗子</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Granton Zhuang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  

  

  

</body>
</html>
